package com.lightboat.web.controller.crm;

import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lightboat.common.annotation.Log;
import com.lightboat.common.core.controller.BaseController;
import com.lightboat.common.core.domain.AjaxResult;
import com.lightboat.common.core.domain.BaseEntity;
import com.lightboat.common.core.page.TableDataInfo;
import com.lightboat.common.enums.BusinessType;
import com.lightboat.common.utils.SecurityUtils;
import com.lightboat.system.domain.CrmOrder;
import com.lightboat.system.domain.CrmPerformancePlan;
import com.lightboat.system.service.ICrmOrderService;
import com.lightboat.system.service.ICrmPerformancePlanService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * 业绩计划Controller
 *
 * @author lightboat
 * @date 2025-11-10
 */
@Tag(name = "业绩计划")
@RestController
@RequiredArgsConstructor
@RequestMapping("/system/plan")
public class CrmPerformancePlanController extends BaseController {

    private final ICrmPerformancePlanService crmPerformancePlanService;
    private final ICrmOrderService crmOrderService;

    /**
     * 查询业绩计划列表
     */
    @Operation(summary = "查询业绩计划列表")
    @PreAuthorize("@ss.hasPermi('system:plan:list')")
    @GetMapping("/list")
    public TableDataInfo<CrmPerformancePlan> list(CrmPerformancePlan crmPerformancePlan) {
        startPage();
        crmPerformancePlan.setPerformanceType(2);
        List<CrmPerformancePlan> list = crmPerformancePlanService.selectCrmPerformancePlanList(crmPerformancePlan);
        clearPage();
        if (ObjUtil.isNotEmpty(list)) {
            list.parallelStream().forEach(plan -> {
                if (plan.getTurnoverAmount() == null) {
                    CrmOrder crmOrder = crmOrderService.getOne(
                            Wrappers.<CrmOrder>query()
                                    .select("sum(COALESCE(total_amount)) as totalAmount")
                                    .eq("salesman_dept_id", plan.getDeptId())
                                    .eq("date_format(create_time,'%Y%m')", plan.getMembers())
                                    .eq("is_write_off", 1)
                    );
                    plan.setTurnoverAmount(Opt.ofNullable(crmOrder).map(CrmOrder::getTotalAmount).orElse(BigDecimal.ZERO));
                }
            });
        }
        return getDataTable(list);
    }

    /**
     * 查询业绩计划列表
     */
    @Operation(summary = "查询我的业绩计划列表")
    @PreAuthorize("@ss.hasPermi('system:user:plan:list')")
    @GetMapping("/user/list")
    public TableDataInfo<CrmPerformancePlan> userList(CrmPerformancePlan crmPerformancePlan) {
        startPage();
        crmPerformancePlan.setUserId(SecurityUtils.getUserId());
        crmPerformancePlan.setPerformanceType(1);
        List<CrmPerformancePlan> list = crmPerformancePlanService.selectCrmPerformancePlanList(crmPerformancePlan);
        clearPage();
        if (ObjUtil.isNotEmpty(list)) {
            list.parallelStream().forEach(plan -> {
                if (plan.getTurnoverAmount() == null) {
                    CrmOrder crmOrder = crmOrderService.getOne(
                            Wrappers.<CrmOrder>query()
                                    .select("sum(COALESCE(total_amount)) as totalAmount")
                                    .eq("salesman_id", plan.getUserId())
                                    .eq("is_write_off", 1)
                    );
                    plan.setTurnoverAmount(Opt.ofNullable(crmOrder).map(CrmOrder::getTotalAmount).orElse(BigDecimal.ZERO));
                }
            });
        }
        return getDataTable(list);
    }

    /**
     * 获取业绩计划详细信息
     */
    @Operation(summary = "获取业绩计划详细信息")
    // @PreAuthorize("@ss.hasPermi('system:plan:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        CrmPerformancePlan crmPerformancePlan = crmPerformancePlanService.selectCrmPerformancePlanById(id);
        if (crmPerformancePlan == null) {
            return error("业绩计划不存在");
        }
        if (crmPerformancePlan.getPerformanceType() == 1) {
            if (!crmPerformancePlan.getUserId().equals(SecurityUtils.getUserId())) {
                return error("无权限查看业绩计划");
            }
            CrmOrder crmOrder = crmOrderService.getOne(
                    Wrappers.<CrmOrder>query()
                            .select("sum(COALESCE(total_amount)) as totalAmount")
                            .eq("salesman_id", crmPerformancePlan.getUserId())
                            .eq("is_write_off", 1)
            );
            crmPerformancePlan.setTurnoverAmount(Opt.ofNullable(crmOrder).map(CrmOrder::getTotalAmount).orElse(BigDecimal.ZERO));

            crmPerformancePlan.setCompletionRate(crmPerformancePlan.getTurnoverAmount().divide(crmPerformancePlan.getTargetAmount(), 2, BigDecimal.ROUND_HALF_UP));
        }else {
            if (!crmPerformancePlan.getDeptId().equals(SecurityUtils.getDeptId())) {
                return error("无权限查看业绩计划");
            }
            // CrmOrder crmOrder = crmOrderService.getOne()
        }
        return success();
    }

    /**
     * 新增业绩计划
     */
    @Operation(summary = "新增业绩计划")
    // @PreAuthorize("@ss.hasPermi('system:plan:add')")
    @Log(title = "业绩计划", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated(BaseEntity.Create.class) @RequestBody CrmPerformancePlan crmPerformancePlan) {
        crmPerformancePlan.setUserId(SecurityUtils.getUserId());
        return toAjax(crmPerformancePlanService.insertCrmPerformancePlan(crmPerformancePlan));
    }

    /**
     * 修改业绩计划
     */
    @Operation(summary = "修改业绩计划")
    // @PreAuthorize("@ss.hasPermi('system:plan:edit')")
    @Log(title = "业绩计划", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated(CrmPerformancePlan.Update.class) @RequestBody CrmPerformancePlan crmPerformancePlan) {
        CrmPerformancePlan performancePlan = crmPerformancePlanService.getById(crmPerformancePlan.getId());
        if (performancePlan == null) {
            return error("业绩计划不存在");
        }
        Long userId = SecurityUtils.getUserId();
        int result = 0;
        if (performancePlan.getPerformanceType() == 1) {
            if (!userId.equals(performancePlan.getUserId())) {
                return error("无权限修改业绩计划");
            }
            crmPerformancePlan.setUserId(userId);
            result = crmPerformancePlanService.updateCrmPerformancePlan(performancePlan);
        }else {
            result = crmPerformancePlanService.updateCrmPerformancePlan(performancePlan);
        }
        return toAjax(result);
    }

    /**
     * 删除业绩计划
     */
    @Operation(summary = "删除业绩计划")
    @PreAuthorize("@ss.hasPermi('system:plan:remove')")
    @Log(title = "业绩计划", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(crmPerformancePlanService.deleteCrmPerformancePlanByIds(ids));
    }
}
